package com.jams.goodox.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.activity.mine.personal.ConnectPersonalCompanyActivity;
import com.jams.goodox.entity.User;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.widget.BirthdayDateTimePickerDialog;
import com.jams.library.fresco.FrescoUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;

/**
 * Created by jams on 2017/5/9.
 * ***
 * Tel: ***
 */

public class UserUtils {

    public static final String UserStatusUnLink = "0";//未绑定企业
    public static final String UserStatusUnAuth = "1";//绑定企业未授权
    public static final String UserStatusGetAll = "2";//得到企业授权
    public static final String UserStatusGetAuditing = "3";//绑定待审核
    public static final String UserStatusGetReject = "4";//绑定被拒绝


    public interface ChangeSexListener {
        void sex(String sex);
    }

    /**
     * 修改性别（在Activity里面使用）
     *
     * @param activity 必须继承BaseActivity
     */
    public static void editSex(final Activity activity, final String sex, final ChangeSexListener changeSexListener) {
        int s = 0;
        if (sex != null && sex.equalsIgnoreCase("2")) {
            s = 1;
        }
        new MaterialDialog.Builder(activity).title("请选择").items(R.array.sex).itemsCallbackSingleChoice(s,
                new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                        if (!isSameChoice(sex, which)) {
                            ((BaseActivity) activity).enqueue(((BaseActivity) activity).createCallService(MineService.class).modifyUserSex(which + 1 + ""), new RetrofitCallbackListener<BaseEntity>() {
                                @Override
                                public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                                    ToastUtil.showLong(activity, "修改成功");
                                    changeSexListener.sex(which + 1 + "");
                                }

                                @Override
                                public void onError(String msg) {

                                }
                            });
                        }
                        return false;
                    }

                }).widgetColor(ContextCompat.getColor(activity, R.color.main_theme))
//                .positiveColor(ContextCompat.getColor(activity, R.color.main_theme))
                .positiveText("确认").show();
    }

    // 性别是不是没有改变
    public static boolean isSameChoice(String sex, int which) {
        if (sex == null)
            return false;
        if (which == 0 && sex.equalsIgnoreCase("1"))
            return true;
        return which == 1 && sex.equalsIgnoreCase("2");
    }

    public interface ChangeBirthdayListener {
        void birthday(String birth);
    }

    /**
     * 更新生日 仅支持在Activity中
     *
     * @param activity 必须继承BaseActivity
     * @param birthDay
     * @param changeBirthdayListener
     */
    static String birthTime;

    public static void updateBirthday(final Activity activity, final String birthDay, final ChangeBirthdayListener changeBirthdayListener) {
        birthTime = birthDay;
        int year;
        int month;
        int day;
        if (!TextUtils.isEmpty(birthTime)) {
            String dates[] = birthTime.split("-");
            year = Integer.parseInt(dates[0]);
            month = Integer.parseInt(dates[1]);
            day = Integer.parseInt(dates[2]);
        } else {
            year = 1997;
            month = 01;
            day = 01;
        }
        BirthdayDateTimePickerDialog dialog = new BirthdayDateTimePickerDialog(activity, year, month, day);
        /**
         * 实现接口
         */
        dialog.setOnDateTimeSetListener(new BirthdayDateTimePickerDialog.OnBirthDateTimeSetListener() {

            @Override
            public void OnDateTimeSet(AlertDialog dialog, int year, int month, int day) {

                // changeTime(date, hours);
                birthTime = DayUtils.getBirthdayEntime(year, month, day);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String currentTime = formatter.format(new Date());
                if (birthTime.substring(0, 4).equals(currentTime.substring(0, 4))) {
                    if (Integer.valueOf(birthTime.substring(5, 7)) > Integer.valueOf(currentTime.substring(5, 7))) {
                        ToastUtil.show(activity, "出生日期不能大于当前日期");
                        return;
                    }
                    if (Integer.valueOf(birthTime.substring(5, 7)) == Integer.valueOf(currentTime.substring(5, 7)) && Integer.valueOf(birthTime.substring(8, 10)) > Integer.valueOf(currentTime.substring(8, 10))) {
                        ToastUtil.show(activity, "出生日期不能大于当前日期");
                        return;
                    }
                }
                ((BaseActivity) activity).enqueue(((BaseActivity) activity).createCallService(MineService.class).modifyUserBirthday(birthTime), new RetrofitCallbackListener<BaseEntity>() {
                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                        ToastUtil.showShort(activity, "修改成功");
                        changeBirthdayListener.birthday(birthTime);
                    }

                    @Override
                    public void onError(String msg) {

                    }
                });
            }
        });
        dialog.show();
    }

    /**
     * 此方法获取是否企业账户登录
     *
     * @return true 企业账户登录， false 个人账户登录
     */
    public static boolean isCompanyAccount() {
        return DataCacheManager.getInstance().getUser().isCompanyAccount();
    }

    /**
     * 此方法判断账户是否授权
     *
     * @return true 通过 false 未通过or授权
     */
    public static boolean isVerifier() {
        return UserStatusGetAll.equalsIgnoreCase(DataCacheManager.getInstance().getUser().getRepresent());
    }

    /**
     * 个人是否绑定公司：个人功能需求
     *
     * @return true:没有关联公司 false：绑定
     */
    public static boolean isUnLinkCompany() {
        return UserStatusUnLink.equalsIgnoreCase(DataCacheManager.getInstance().getUser().getRepresent()) //未绑定
                || UserStatusGetAuditing.equalsIgnoreCase(DataCacheManager.getInstance().getUser().getRepresent())//绑定申请还在申请中
                || UserStatusGetReject.equalsIgnoreCase(DataCacheManager.getInstance().getUser().getRepresent());//申请被拒绝
    }


    /**
     * 仅显示单按钮的对话框：如知道了
     */
    public static void showUnVerifierDialog(Context context) {
        new MaterialDialog.Builder(context).content(R.string.unVerifier).positiveText("知道了").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.cancel();
            }
        }).show();
    }

    /**
     * 个人用户未关联公司，需要跳转到关联公司页面
     *
     * @param context 所在页面，用于承载dialog的窗口
     * @param msg     提示信息
     */
    public static void showVerifierDialog(final Context context, String msg) {
        new MaterialDialog.Builder(context).content(msg).onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                context.startActivity(new Intent(context, ConnectPersonalCompanyActivity.class));
                dialog.cancel();
            }
        }).positiveText("确定").onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.cancel();
            }
        }).negativeText("取消").show();
    }

    /**
     * 未审核通过，需要自定义点击事件
     *
     * @param context
     * @param msg          提示文案
     * @param doUnVerifier 点击事件
     */
    public static void showVerifierDialog(final Context context, String msg, MaterialDialog.SingleButtonCallback doUnVerifier) {
        new MaterialDialog.Builder(context).content(msg).onPositive(doUnVerifier).positiveText("确定").onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.cancel();
            }
        }).negativeText("取消").show();
    }

    public static void setSexImage(User user, ImageView imageView) {
        if (user == null) {
            imageView.setVisibility(View.GONE);
            return;
        }
        if ("1".equals(user.getSex())) {//男
            imageView.setImageResource(R.mipmap.male_icon);
        } else if ("2".equals(user.getSex())) {//女
            imageView.setImageResource(R.mipmap.female_icon);
        } else {
            imageView.setImageResource(R.mipmap.none_sex);
        }
    }

    public static void setSexImage(User user, SimpleDraweeView imageView) {
        if (user == null) {
            imageView.setVisibility(View.GONE);
            return;
        }
        if ("1".equals(user.getSex())) {//男
            FrescoUtil.loadRes(TownApplicationLike.getInstance(),imageView, R.mipmap.male_icon);
        } else if ("2".equals(user.getSex())) {//女
            FrescoUtil.loadRes(TownApplicationLike.getInstance(),imageView, R.mipmap.female_icon);
        } else {
            FrescoUtil.loadRes(TownApplicationLike.getInstance(),imageView, R.mipmap.none_sex);
        }
    }

    //判断是否是授权的，不是的话给提示并且返回false
    public static boolean checkIsCompetent(){
        if(isVerifier()){
            return true;
        }else{
            ToastUtil.show(TownApplicationLike.getInstance(),R.string.unVerifier);
            return false;
        }
    }
}
